package cn.lix.sc.rpc.client.controller;

import cn.lix.sc.rpc.commons.annotations.LogPrinter;
import cn.lix.sc.rpc.impl.common.annotations.RpcClient;
import cn.lix.sc.rpc.impl.common.annotations.RpcService;
import cn.lix.sc.rpc.impl.common.utils.JsonUtil;
import cn.lix.sc.rpc.service.demo.dto.User;
import cn.lix.sc.rpc.service.demo.service.EnhancedFileService;
import cn.lix.sc.rpc.service.demo.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 增强的测试控制器，展示多种内容类型的RPC调用
 *
 * @author lix
 * @date 2024
 */
@Api(tags = "增强测试控制器", description = "支持多种内容类型的RPC调用测试接口")
@RestController
@RequestMapping("/enhanced-test")
public class EnhancedTestController {

    private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());

    /**
     * 增强的文件服务客户端，支持多种内容类型
     */
    @RpcClient(
            serverName = "${rpc.server.server-name}",
            beanName = "enhancedFileService",
            contentTypes = {
                    RpcService.ContentType.JSON,
                    RpcService.ContentType.MULTIPART,
                    RpcService.ContentType.OCTET_STREAM,
                    RpcService.ContentType.TEXT_PLAIN
            },
            maxFileSize = 50 * 1024 * 1024 // 50MB
    )
    private EnhancedFileService enhancedFileService;
    /**
     * 增强的文件服务客户端，支持多种内容类型
     */
    @RpcClient(serverName = "${rpc.server.server-name}", beanName = "testServiceImpl2")
    private TestService testService;



    /**
     * 测试json数据传输
     */
    @ApiOperation(value = "测试json数据传输")
    @LogPrinter
    @GetMapping("/json")
    public ResponseEntity<String> testJSON() {
        try {
            log.info("测试json数据传输");

            User xiaoming = testService.hello(30, "xiaoming", true);

            return ResponseEntity.ok(JsonUtil.obj2String(xiaoming));
        } catch (Exception e) {
            log.error("测试json数据传输", e);
            return ResponseEntity.badRequest().body("测试json数据传输: " + e.getMessage());
        }
    }

    /**
     * 测试文件上传
     */
    @ApiOperation(value = "文件上传测试", notes = "测试通过RPC进行文件上传")
    @LogPrinter
    @PostMapping("/upload")
    public ResponseEntity<String> testFileUpload(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile file,
                                                 @ApiParam(value = "文件描述") @RequestParam(value = "description", required = false) String description) {
        try {
            log.info("接收文件上传测试请求: 文件名={}, 大小={} bytes", file.getOriginalFilename(), file.getSize());

            String result = enhancedFileService.uploadFile(file, description != null ? description : "测试上传");

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("文件上传测试失败", e);
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 测试文件下载
     */
    @ApiOperation(value = "文件下载测试", notes = "测试通过RPC进行文件下载")
    @LogPrinter
    @GetMapping("/download")
    public ResponseEntity<byte[]> testFileDownload(@ApiParam(value = "文件名", required = true) @RequestParam String fileName) {
        try {
            log.info("请求文件下载: {}", fileName);

            byte[] fileData = enhancedFileService.downloadFile(fileName);

            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                    .body(fileData);
        } catch (Exception e) {
            log.error("文件下载测试失败", e);
            return ResponseEntity.badRequest().body(("下载失败: " + e.getMessage()).getBytes());
        }
    }

    /**
     * 测试流式数据处理
     */
    @ApiOperation(value = "流式数据处理测试", notes = "测试通过RPC进行流式数据处理")
    @LogPrinter
    @PostMapping("/stream")
    public ResponseEntity<byte[]> testStreamProcessing(@ApiParam(value = "二进制数据", required = true) @RequestBody byte[] data,
                                                       @ApiParam(value = "处理操作类型", defaultValue = "reverse") @RequestParam(value = "operation", defaultValue = "reverse") String operation) {
        try {
            log.info("流式数据处理测试: 数据大小={} bytes, 操作={}", data.length, operation);

            InputStream inputStream = new ByteArrayInputStream(data);
            byte[] result = enhancedFileService.processStream(inputStream, operation);

            return ResponseEntity.ok()
                    .header("Content-Type", "application/octet-stream")
                    .body(result);
        } catch (Exception e) {
            log.error("流式数据处理测试失败", e);
            return ResponseEntity.badRequest().body(("处理失败: " + e.getMessage()).getBytes());
        }
    }

    /**
     * 测试文本处理
     */
    @ApiOperation(value = "文本处理测试", notes = "测试通过RPC进行文本处理")
    @LogPrinter
    @PostMapping("/text")
    public ResponseEntity<String> testTextProcessing(@ApiParam(value = "文本内容", required = true) @RequestBody String content) {
        try {
            log.info("文本处理测试: 内容长度={} 字符", content.length());

            String result = enhancedFileService.processText(content);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("文本处理测试失败", e);
            return ResponseEntity.badRequest().body("处理失败: " + e.getMessage());
        }
    }

    /**
     * 测试图片处理
     */
    @ApiOperation(value = "图片处理测试", notes = "测试通过RPC进行图片处理")
    @LogPrinter
    @PostMapping("/image")
    public ResponseEntity<byte[]> testImageProcessing(@ApiParam(value = "图片文件", required = true) @RequestParam("image") MultipartFile image,
                                                      @ApiParam(value = "处理操作类型", defaultValue = "resize") @RequestParam(value = "operation", defaultValue = "resize") String operation) {
        try {
            log.info("图片处理测试: 文件名={}, 大小={} bytes, 操作={}",
                    image.getOriginalFilename(), image.getSize(), operation);

            byte[] imageData = image.getBytes();
            byte[] result = enhancedFileService.processImage(imageData, operation);

            return ResponseEntity.ok()
                    .header("Content-Type", "image/jpeg")
                    .body(result);
        } catch (IOException e) {
            log.error("图片处理测试失败", e);
            return ResponseEntity.badRequest().body(("处理失败: " + e.getMessage()).getBytes());
        }
    }

    /**
     * 测试批量文件处理
     */
    @ApiOperation(value = "批量文件处理测试", notes = "测试通过RPC进行批量文件处理")
    @LogPrinter
    @PostMapping("/batch")
    public ResponseEntity<String> testBatchProcessing(@ApiParam(value = "文件JSON配置", required = true) @RequestBody String filesJson,
                                                      @ApiParam(value = "处理操作类型", defaultValue = "compress") @RequestParam(value = "operation", defaultValue = "compress") String operation) {
        try {
            log.info("批量处理测试: 操作={}", operation);

            String result = enhancedFileService.batchProcessFiles(filesJson, operation);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量处理测试失败", e);
            return ResponseEntity.badRequest().body("处理失败: " + e.getMessage());
        }
    }

    /**
     * 真实文件上传（支持多个文件）
     */
    @ApiOperation(value = "真实文件上传", notes = "支持单个或多个文件的真实上传功能")
    @LogPrinter
    @PostMapping("/real-upload")
    public ResponseEntity<String> testRealFileUpload(@ApiParam(value = "上传的文件列表", required = true) @RequestParam("files") MultipartFile[] files,
                                                     @ApiParam(value = "上传描述") @RequestParam(value = "description", required = false) String description) {
        try {
            if (files == null || files.length == 0) {
                return ResponseEntity.badRequest().body("请选择要上传的文件");
            }

            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.append("上传结果:\n");

            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                if (file.isEmpty()) {
                    resultBuilder.append(String.format("文件 %d: 文件为空，跳过\n", i + 1));
                    continue;
                }

                log.info("处理文件 {}: 文件名={}, 大小={} bytes", i + 1, file.getOriginalFilename(), file.getSize());

                String fileDescription = description != null ? description + " - 文件" + (i + 1) : "文件上传 - " + (i + 1);
                String result = enhancedFileService.uploadFile(file, fileDescription);

                resultBuilder.append(String.format("文件 %d (%s): %s\n", i + 1, file.getOriginalFilename(), result));
            }

            return ResponseEntity.ok(resultBuilder.toString());
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResponseEntity.badRequest().body("上传失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查
     */
    @ApiOperation(value = "健康检查", notes = "检查增强RPC客户端运行状态")
    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("Enhanced RPC Client is running");
    }
} 